<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24/024
 * Time: 22:38
 */

namespace app\api\model;
use think\Model;


class Token extends Base
{
    /**
     * token校验
     * @param token string
     * @return array|null|\PDOStatement|string|Model
     */
    public function _check($token){
        if(empty($token)){
            $this->error = '缺少token';
            return false;
        }
        $member = $this->where([['token', '=', $token], ['deadline', '>=', time()]])->find();
        if(empty($member)){
            $this->error = '请重新登陆';
            return false;
        }
        return true;
    }
    
    /**
    * 通过用户id查找token
    * @param mid 用户id
    */
    public function _getTokenById($mid){
        return $this->where([['mid', '=', $mid]])->find();
    }
    
    /**
    * 通过token查找用户
    * @param token 用户token
    */
    public function _getMemberByToken($token){
        return $this->where([['token', '=', $token]])->find();
    }
    
    /**
    * 创建token
    * @param mid 用户id
    */
    public function _createToken($mid){
        $data = $this->_getTokenById($mid);
        $token = createToken($mid);
        
        $config = $this->getConfig();
        $deadline = time() + 10080 * 60;
        if(empty($data)){
            $insert_data = [
                'mid' => $mid,
                'token' => $token,
                'deadline' => $deadline,
                'created' => time(),
            ];
            
            $ret = $this->save($insert_data);
            if(!$ret){
                $this->error = 'token创建失败';
                return false;
            }
            return true;
        }else{
            $ob = $this->where([['mid', '=', $mid]])->find();
            $ob->token = $token;
            
            $ob->deadline = $deadline;
            $ret = $ob->save();
            if(!$ret){
                $this->error = 'token创建失败';
                return false;
            }
            
            return true;
        }
    }
    
}